package com.gf.framework.weblog.aspect;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gf.framework.weblog.annotation.FunctionLog;
import com.gf.framework.weblog.model.FunctionLogInfo;
import com.gf.framework.weblog.service.FunctionLogServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.ArrayList;

/**
 * @author gaofei
 * @date 2022/6/14 22:06
 */
@Aspect
@Component
public class FunctionLogAspect {
    @Value("${spring.application.name:未知}")
    private String appName;

    @Autowired
    private FunctionLogServiceImpl functionLogService;

    @Around("@annotation(com.gf.framework.weblog.annotation.FunctionLog)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        FunctionLog functionLog = method.getAnnotation(FunctionLog.class);

        Object[] args = joinPoint.getArgs();

        FunctionLogInfo functionLogInfo = new FunctionLogInfo();
        functionLogInfo.setAppName(appName);
        functionLogInfo.setFunctionName(StringUtils.isBlank(functionLog.functionName()) ? method.getName() : functionLog.functionName());
        functionLogInfo.setArgs(args);
        functionLogInfo.setCallTime(LocalDateTime.now());
        long nowTime = System.currentTimeMillis();

        try {
            Object ret = joinPoint.proceed();
            functionLogInfo.setSuccess(true);
            if (functionLog.saveRet()) {
                functionLogInfo.setRet(ret);
            }
            return ret;
        } catch (Throwable e) {
            functionLogInfo.setSuccess(false);
            functionLogInfo.setErrorMessage(e.getMessage());
            StackTraceElement[] elements = e.getStackTrace();
            if (elements != null && elements.length > 0) {
                functionLogInfo.setStackList(new ArrayList<>(10));
                for (int i = 0; i < 10 && i < elements.length; i++) {
                    functionLogInfo.getStackList().add(elements[i].toString());
                }
            }
            throw e;
        } finally {
            functionLogInfo.setTimeConsuming((int) (System.currentTimeMillis() - nowTime));
            functionLogService.send(functionLogInfo);
        }
    }
}
